package service

import (
	"QHMedLink/model"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 1. 创建收藏记录（自动处理唯一约束）
func CreateFavorite(db *gorm.DB, userID, infoID uint, infoType model.InfoType) error {
	favorite := &model.Favorite{
		UserID:   userID,
		InfoID:   infoID,
		InfoType: infoType,
	}
	// 使用 Clauses 处理重复插入（自动忽略冲突）
	if err := db.Clauses(clause.OnConflict{DoNothing: true}).Create(favorite).Error; err != nil {
		return err
	}
	return nil
}

// 2. 按用户查询所有收藏
func GetFavoritesByUser(db *gorm.DB, userID uint) ([]model.Favorite, error) {
	var favorites []model.Favorite
	if err := db.Where("user_id = ?", userID).Find(&favorites).Error; err != nil {
		return nil, err
	}
	return favorites, nil
}

// 3. 按复合条件查询
func GetFavoriteByCompositeKey(db *gorm.DB, userID, infoID uint, infoType model.InfoType) (*model.Favorite, error) {
	var favorite model.Favorite
	if err := db.Where("user_id = ? AND info_id = ? AND info_type = ?",
		userID, infoID, infoType).First(&favorite).Error; err != nil {
		return nil, err
	}
	return &favorite, nil
}

// 4. 删除收藏记录
func DeleteFavorite(db *gorm.DB, favoriteID uint) error {
	return db.Model(&model.Favorite{}).
		Where("favorite_id = ?", favoriteID).
		Update("is_deleted", true).Error
}

// 5. 事务操作：批量删除收藏
func BatchDeleteFavorites(db *gorm.DB, userID uint, ids []uint) error {
	return db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&model.Favorite{}).
			Where("user_id = ? AND favorite_id IN ?", userID, ids).
			Update("is_deleted", true).Error; err != nil {
			return err
		}
		return nil
	})
}
